package com.adopapa.wechatapi.util;

import java.util.UUID;
import java.util.Map;
import java.util.HashMap;
import java.util.Formatter;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;

public class Sign4Js {
	public static void main(String[] args) {
		String jsapi_ticket = "sM4AOVdWfPE4DxkXGEs8VHpyC4fZdg1jQuNtkTUHQsAy9a8MtTQTLDfZ--loFInPzeZOm460yGXY5AL71P0YBA";

/*		System.out.println(WeChatUtil.sign4JsApi("sM4AOVdWfPE4DxkXGEs8VHpyC4fZdg1jQuNtkTUHQsAy9a8MtTQTLDfZ--loFInPzeZOm460yGXY5AL71P0YBA", "adopapa",
				"1429968187", "http://118.244.237.56/app/testjs/toTestjs.do"));*/

		// 注意 URL 一定要动态获取，不能 hardcode
		String url = "http://118.244.237.56/app/testjs/toTestjs.do";
		Map<String, String> ret = sign(jsapi_ticket, url);
		for (Map.Entry entry : ret.entrySet()) {
			System.out.println(entry.getKey() + ", " + entry.getValue());
		}
	};

	public static Map<String, String> sign(String jsapiTicket, String url) {
		Map<String, String> ret = new HashMap<String, String>();
		 String nonce_str = createNonceStr();
		 String timestamp = createTimestamp();
		// String nonce_str = "adopapa";
		// String timestamp = "1429968187";
		String string1;
		String signature = "";

		// 注意这里参数名必须全部小写，且必须有序
		string1 = "jsapi_ticket=" + jsapiTicket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
		System.out.println(string1);

		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(string1.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		ret.put("url", url);
		ret.put("jsapiTicket", jsapiTicket);
		ret.put("nonceStr", nonce_str);
		ret.put("timestamp", timestamp);
		ret.put("signature", signature);

		return ret;
	}

	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;
	}

	private static String createNonceStr() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}

	private static String createTimestamp() {
		return Long.toString(System.currentTimeMillis() / 1000);
	}
}